package com.yuyou.fn.educational.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.sun.tools.corba.se.idl.StringGen;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.educational.entity.Period;
import com.yuyou.fn.educational.entity.PeriodSegment;
import com.yuyou.fn.educational.entity.Product;
import com.yuyou.fn.educational.service.IPeriodSegmentService;
import com.yuyou.fn.educational.service.IPeriodService;
import com.yuyou.fn.educational.service.IProductService;
import com.yuyou.fn.educational.vo.ChargeSettingQueryVo;
import com.yuyou.fn.educational.vo.ChargeSettingSaveUpdateVo;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.platform.service.IProvinceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.yuyou.fn.educational.mapper.ChargeSettingMapper;
import com.yuyou.fn.educational.entity.ChargeSetting;
import com.yuyou.fn.educational.service.IChargeSettingService;
import com.github.wens.framework.service.impl.SuperServiceImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * ChargeSetting 表数据服务层接口实现类
 *
 */
@Service
public class ChargeSettingServiceImpl extends SuperServiceImpl<ChargeSettingMapper, ChargeSetting,Long> implements IChargeSettingService {

    @Resource
    private IPeriodService periodService;

    @Resource
    private IProductService productService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private IPeriodSegmentService periodSegmentService;

    @Override
    public Page<ChargeSetting> findChargeSettingPageByQueryVo(ChargeSettingQueryVo chargeSettingQueryVo,int pageNo,int pageSize) {
        Example<ChargeSetting> example=ChargeSetting.createExample();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria,chargeSettingQueryVo);
        return this.findPageByExample(example,pageNo,pageSize);
    }

    @Override
    public void saveOrUpdateChargeSettingByVo(ChargeSettingSaveUpdateVo chargeSettingSaveUpdateVo) {
        if (chargeSettingSaveUpdateVo.getStartLectureNo()>chargeSettingSaveUpdateVo.getEndLectureNo()){
            throw new BusException("开始讲次不能大于结束讲次");
        }
        Principals.Principal principal=Principals.get();

        String productIds=chargeSettingSaveUpdateVo.getProductIds();
        AreaTeam areaTeam=areaTeamService.findById(chargeSettingSaveUpdateVo.getAreaTeamId());

        List<Product> productList=null;
        if (StringUtils.isEmpty(productIds)){
            productList=productService.findBaseProductByAreaTeamId(chargeSettingSaveUpdateVo.getAreaTeamId());
        }else {
            productList=productService.findByIds(Utils.toLongIds(chargeSettingSaveUpdateVo.getProductIds()));
        }

        List<Long> productNames = BeanUtils.toList(productList, "name");
        List<Long> productIdList = BeanUtils.toList(productList, "productId");
        Map<Long, Product> productMap = BeanUtils.toMap(productList, "productId");
        //查询该期数该段次有效的记录防止存在多条
        this.checkHaveSetting(productIdList,productMap,chargeSettingSaveUpdateVo.getPeriodId(),chargeSettingSaveUpdateVo.getChargeSegment(),chargeSettingSaveUpdateVo.getChargeSettingId());


        Period period=periodService.findById(chargeSettingSaveUpdateVo.getPeriodId());
        ChargeSetting chargeSetting=new ChargeSetting();
        BeanUtils.copyProperties(chargeSetting,chargeSettingSaveUpdateVo);
        chargeSetting.setAreaTeamId(areaTeam.getAreaTeamId());
        chargeSetting.setAreaTeamName(areaTeam.getName());
        chargeSetting.setPeriodId(period.getPeriodId());
        chargeSetting.setPeriodName(period.getPeriodName());
        chargeSetting.setOperatorId(principal.id);
        chargeSetting.setOperatorName(principal.name);
        chargeSetting.setUpdateTime(TimeUtils.now());
        chargeSetting.setProductIds(StringUtils.join(productIdList,","));
        chargeSetting.setProductNames(StringUtils.join(productNames,","));
        if (chargeSettingSaveUpdateVo.getChargeSettingId()==null){
            chargeSetting.setCreateTime(TimeUtils.now());
            this.insert(chargeSetting);
        }else {
            this.updateSelectiveById(chargeSetting);
        }
    }

    @Override
    public List<ChargeSetting> findByPeriodIdChargeSegmentStatus(Long periodId, Integer chargeSegment, Integer status) {

        Example<ChargeSetting> example=ChargeSetting.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("periodId",periodId).andEqualTo("chargeSegment",chargeSegment) .andEqualTo("status",status);
        return this.findListByExample(example);
    }

    @Override
    public void checkHaveSetting(List<Long> productIds,Map<Long, Product> productMap,Long periodId, Integer chargeSegment,Long chargeSettingId) {
        List<Long> checkProductIds = new ArrayList<>(productIds);
        List<ChargeSetting> chargeSettingList=this.findByPeriodIdChargeSegmentStatus(periodId,chargeSegment,1);
        if (chargeSettingId!=null && !chargeSettingList.isEmpty()){
            chargeSettingList = chargeSettingList.stream().filter(chargeSetting -> !chargeSetting.getChargeSettingId().equals(chargeSettingId)).collect(Collectors.toList());
        }
        List<String> allProductIds = BeanUtils.toList(chargeSettingList, "productIds");
        List<Long> allProductIdList=Utils.toLongIds(StringUtils.join(allProductIds,","));
        if (!allProductIdList.isEmpty()){
            checkProductIds.retainAll(allProductIdList);
            if (!checkProductIds.isEmpty()){
                StringBuffer stringBuffer=new StringBuffer();
                for (int i=0;i<checkProductIds.size();i++){
                    Product product=productMap.get(checkProductIds.get(i));
                    stringBuffer.append(product.getName());
                    if (i<checkProductIds.size()){
                        stringBuffer.append(",");
                    }
                }
                throw new BusException("["+stringBuffer.toString()+"]已存在设置");
            }
        }
    }
}